package com.powernode.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.powernode.entity.Goods;
import com.powernode.entity.Orders;
import com.powernode.mapper.GoodsMapper;
import com.powernode.mapper.OrdersMapper;
import com.powernode.service.GoodsService;
import com.powernode.service.OrdersService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * 订单 业务逻辑层 实现类
 */
@Service
@Slf4j
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper , Orders> implements OrdersService {

    @Resource
    private GoodsService goodsService;

    /**
     * 下订单功能  --> 获取秒杀商品信息 | 插入订单信息   |  更新商品库存信息
     * @param orders : 订单信息
     * @return : 返回
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int doOrder(Orders orders) {
        log.info("根据传过来的订单消息 进行下订单功能的实现 , 订单消息为 : {}" , orders);
        // 根据 商品id 查询商品信息
        Goods goods = goodsService.getById(orders.getGoodsId());
        // 判断 商品是否 存在
        if (goods == null) {
           throw new RuntimeException("该商品不存在");
        }
        // 判断 商品数量
        if (goods.getStore() <= 0) {
            throw new RuntimeException("商品已经抢完");
        }

        // 进行 减库存操作
        LambdaUpdateWrapper<Goods> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.setSql("store = store - 1");
        updateWrapper.eq(Goods::getId , goods.getId());
        // 底层 --> SqlHelper.retBool(this.getBaseMapper().update(entity, updateWrapper));
        boolean update = goodsService.update(updateWrapper);
        if (!update) {
            throw new RuntimeException("扣减库存失败 , 商品id为 : " + orders.getGoodsId());
        }

        // 插入订单数据
        // int insert = baseMapper.insert(orders);
        // save的底层  -->  SqlHelper.retBool(this.getBaseMapper().insert(entity));
        boolean save = this.save(orders);
        if (!save) {
            throw new RuntimeException("插入订单失败");
        }

        return 1;
    }
}
